const BASE_URL = 'http://127.0.0.1:3000';

export async function request(
  endpoint: string,
  { body, method, headers }: { body?: object | null; method: string; headers?: HeadersInit } = {
    method: 'GET',
  }
) {
  const headersByDefault = { 'Content-Type': 'application/json' };
  const config = {
    method,
    headers: {
      ...headersByDefault,
      ...headers,
    },
    body: body ? JSON.stringify(body) : null,
  };

  const response = await fetch(`${BASE_URL}/${endpoint}`, config);
  if (response.ok) {
    return {
      content: await response.json(),
      count: response.headers.get('X-Total-Count') ?? null,
    };
  }
  const errorMessage = await response.text();
  return Promise.reject(new Error(errorMessage));
}
